package whf.framework.meta.web;

import java.util.List;

import whf.framework.entity.AbstractEntity;
import whf.framework.entity.Entity;
import whf.framework.lucene.IndexUtils;
import whf.framework.meta.entity.Object;
import whf.framework.meta.entity.View;
import whf.framework.meta.service.ObjectServiceImp;
import whf.framework.meta.service.ViewServiceImp;
import whf.framework.service.Service;
import whf.framework.util.BeanFactory;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-05-31
 */
@SuppressWarnings("unchecked")
public class ObjectAction extends WebDispatchAction {

	@Override
	public WebForward list(AbstractEntity webEntity, WebData data) throws Exception {
		List list = super.getService().find("select distinct t.subModule from " + Object.class.getName() +" t order by t.subModule");
		data.setAttribute("submodules", list);
		webEntity.setWebMethod("list");
		return super.list(webEntity, data);
	}

	@Override
	public WebForward update(AbstractEntity webEntity, WebData data) throws Exception {
		super.update(webEntity, data);
		return prepareUpdate(webEntity, data);
	}

	/**
	 * 通过对象创建一个对应的视图,视图对象参考此对象,视图中所有属性参考对象的属性
	 * @modify wanghaifeng Sep 27, 2006 10:05:00 PM
	 * @param mapping
	 * @param baseForm
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public WebForward createReferenceView(AbstractEntity webEntity, WebData data) throws Exception {
		whf.framework.meta.entity.Object obj = ObjectServiceImp.getObjectService().findByPrimaryKeyWithoutLazy(webEntity.getId());
		View view = new View(obj);
		ViewServiceImp.getViewService().create(view);
		return super.prepareUpdate(webEntity, data);
	}
	
	/**
	 * 创建实体索引
	 * @author king
	 * @create 2008-1-26 下午06:28:52
	 * @param webEntity
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public WebForward indexEntities(AbstractEntity webEntity, WebData data) throws Exception {
		long[] ids = data.getLongParameters("id", 0);
		for(long objectId: ids) {
			if(objectId == 0) continue;
			Object obj = ObjectServiceImp.getObjectService().findByPrimaryKey(objectId);
			Service<? extends Entity> service = (Service<? extends Entity>)BeanFactory.getBean(obj.getServiceName());
			List<? extends Entity> list = service.findAll();
			IndexUtils.getInstance().indexEntities(list);
		}
		return this.list(webEntity, data);
	}
} 